import React, { useState } from "react";
import { Outlet, useNavigate, useLocation } from "react-router-dom";
import { Menu, Layout } from "antd";

import router from "@/route/index";
const { Sider } = Layout;
function getItem(label, key, children) {
  return {
    key,
    children,
    label,
  };
}
const items = [
  // getItem("关于", "/about"),
  // getItem("User", "/User", [getItem("Tom", "/User/Tom")]),
];

export default function MyMenu() {
  const currentPath = useLocation(); //hooks不能在下面点击事件函数中使用
  const useRouter = useNavigate(); //路由跳转的hooks

  // const rootSubmenuKeys = ["sub1", "sub2"];
  const [collapsed, setCollapsed] = useState(false);

  const showItems = (item) => {
    if (item.children && item.children.length > 0) {
      const arr = item.children.map((e, i) => {
        return getItem(e.mate.title, e.path);
      });
      return getItem(item.mate.title, item.path, arr);
    } else {
    return getItem(item.mate.title, item.path);
    }
  };
  // console.log("first", router[0].children);
  router[0]?.children.forEach((item, index) => {
    items.push(showItems(item));
  });

  /**
   * 默认展开当前选中二级路由
   */
  let openKey = "";
  items.forEach((ele, index) => {
    if (ele.children?.find((e) => e.key == currentPath.pathname)) {
      //判断刷新后当前路由是否是二级菜单
      openKey = ele.key; //当前路由是二级菜单，将当前一级菜单展开
    }
  });
  const [openKeys, setOpenKeys] = useState([openKey]); //设置默认展开的一级菜单

  const onOpenChange = (keys) => {
    //设置只展开一个一级菜单
    const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1);
    // console.log(keys,openKeys,latestOpenKey)

    // if (latestOpenKey && rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
    //   setOpenKeys(keys);
    // } else {
      setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
    // }
  };
  const menuClick = (e) => {
    // console.log("currentPath", currentPath);
    // console.log("1111111", e, useRouter);
    useRouter(e.key);
  };
  return (
    <Sider
      collapsible
      collapsed={collapsed}
      onCollapse={(value) => setCollapsed(value)}
    >
      <div className="demo-logo-vertical" />
      <Menu
        theme="dark"
        defaultSelectedKeys={[currentPath.pathname]}
        selectedKeys={[currentPath.pathname]}
        openKeys={openKeys}
        mode="inline"
        items={items}
        onClick={menuClick}
        onOpenChange={onOpenChange}
      />
    </Sider>
  );
}
